/**
 * AI分析引擎 - 用于分析GitLab提交日志并生成工作报告
 */
class AIAnalysisEngine {
  constructor() {
    // 提交类型分类关键词
    this.commitTypeKeywords = {
      feature: [
        'feat', 'feature', 'add', '新增', '添加', '实现', 'implement',
        'create', 'build', '功能', '特性', '支持', '支持', 'enable'
      ],
      bugfix: [
        'fix', 'bug', '修复', '解决', '修复', 'fix', 'patch', 'hotfix',
        'error', '错误', '问题', 'issue', '缺陷', '故障', 'broken'
      ],
      refactor: [
        'refactor', '重构', '优化', '改进', 'improve', 'optimize',
        'cleanup', '整理', '重构', '重构', '重构', 'refactor'
      ],
      docs: [
        'docs', 'doc', '文档', '说明', 'readme', '注释', 'comment',
        'documentation', 'guide', '教程', 'wiki', '手册'
      ],
      test: [
        'test', '测试', '单元测试', '集成测试', '测试用例', '测试代码',
        'unittest', 'testing', 'spec', 'mock', 'stub'
      ],
      style: [
        'style', '格式', '样式', '格式化', '代码风格', '缩进', '空格',
        'format', 'lint', 'css', '样式'
      ],
      chore: [
        'chore', '构建', '依赖', 'dependency', 'package', '配置',
        'config', '设置', '工具', 'ci', 'cd', '部署'
      ]
    };

    // 关键成就关键词
    this.achievementKeywords = [
      'major', '重要', '重大', '关键', '核心', '里程碑', 'milestone',
      'breakthrough', '突破', '创新', 'optimize', 'performance', '性能',
      'security', '安全', '重构', '架构', 'architecture'
    ];

    // 关键Bug修复关键词
    this.criticalBugKeywords = [
      'critical', '严重', '致命', 'urgent', '紧急', 'crash', '崩溃',
      'data loss', '数据丢失', 'security', '安全漏洞', 'leak', '泄露',
      'broken', '无法使用', '失效', 'corruption', '损坏'
    ];
  }

  /**
   * 分析提交日志并生成报告
   */
  async analyzeCommits(commits, projectName, startDate, endDate) {
    const analysis = {
      totalCommits: commits.length,
      commitTypes: this.classifyCommits(commits),
      dailyCommits: this.analyzeDailyCommits(commits),
      keyAchievements: this.extractKeyAchievements(commits),
      criticalBugfixes: this.extractCriticalBugfixes(commits),
      codeQuality: this.analyzeCodeQuality(commits),
      aiSummary: this.generateAISummary(commits, projectName, startDate, endDate)
    };

    return analysis;
  }

  /**
   * 分类提交类型
   */
  classifyCommits(commits) {
    const types = {
      feature: 0,
      bugfix: 0,
      refactor: 0,
      docs: 0,
      test: 0,
      style: 0,
      chore: 0,
      other: 0
    };

    commits.forEach(commit => {
      const message = (commit.title + ' ' + commit.message).toLowerCase();
      let classified = false;

      // 根据关键词分类
      for (const [type, keywords] of Object.entries(this.commitTypeKeywords)) {
        if (keywords.some(keyword => message.includes(keyword.toLowerCase()))) {
          types[type]++;
          classified = true;
          break;
        }
      }

      if (!classified) {
        types.other++;
      }
    });

    return types;
  }

  /**
   * 分析每日提交趋势
   */
  analyzeDailyCommits(commits) {
    const dailyData = {};
    
    commits.forEach(commit => {
      const date = commit.created_at ? commit.created_at.split('T')[0] : commit.created_at;
      if (date) {
        dailyData[date] = (dailyData[date] || 0) + 1;
      }
    });

    // 转换为数组格式，按日期排序
    return Object.entries(dailyData)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([date, count]) => ({ date, count }));
  }

  /**
   * 提取关键成就
   */
  extractKeyAchievements(commits) {
    const achievements = [];
    
    commits.forEach(commit => {
      const message = (commit.title + ' ' + commit.message).toLowerCase();
      
      if (this.achievementKeywords.some(keyword => message.includes(keyword.toLowerCase()))) {
        achievements.push({
          id: commit.id,
          title: commit.title,
          message: commit.message,
          author: commit.author_name,
          date: commit.created_at,
          type: 'achievement'
        });
      }
    });

    return achievements.slice(0, 5); // 返回前5个关键成就
  }

  /**
   * 提取关键Bug修复
   */
  extractCriticalBugfixes(commits) {
    const bugfixes = [];
    
    commits.forEach(commit => {
      const message = (commit.title + ' ' + commit.message).toLowerCase();
      
      if (this.criticalBugKeywords.some(keyword => message.includes(keyword.toLowerCase()))) {
        bugfixes.push({
          id: commit.id,
          title: commit.title,
          message: commit.message,
          author: commit.author_name,
          date: commit.created_at,
          severity: 'critical'
        });
      }
    });

    return bugfixes.slice(0, 5); // 返回前5个关键Bug修复
  }

  /**
   * 分析代码质量
   */
  analyzeCodeQuality(commits) {
    let totalAdditions = 0;
    let totalDeletions = 0;
    let largeCommits = 0;
    let smallCommits = 0;

    commits.forEach(commit => {
      if (commit.stats) {
        totalAdditions += commit.stats.additions || 0;
        totalDeletions += commit.stats.deletions || 0;
        const totalChanges = (commit.stats.additions || 0) + (commit.stats.deletions || 0);
        
        if (totalChanges > 500) {
          largeCommits++;
        } else if (totalChanges < 10) {
          smallCommits++;
        }
      }
    });

    const avgChangesPerCommit = commits.length > 0 ? Math.round((totalAdditions + totalDeletions) / commits.length) : 0;
    const testCoverage = this.estimateTestCoverage(commits);

    return {
      totalAdditions,
      totalDeletions,
      avgChangesPerCommit,
      largeCommits,
      smallCommits,
      testCoverage,
      qualityScore: this.calculateQualityScore(commits, avgChangesPerCommit, testCoverage)
    };
  }

  /**
   * 估算测试覆盖率
   */
  estimateTestCoverage(commits) {
    let testRelatedCommits = 0;
    
    commits.forEach(commit => {
      const message = (commit.title + ' ' + commit.message).toLowerCase();
      if (this.commitTypeKeywords.test.some(keyword => message.includes(keyword.toLowerCase()))) {
        testRelatedCommits++;
      }
    });

    // 基于测试相关提交的比例估算覆盖率
    const testRatio = commits.length > 0 ? testRelatedCommits / commits.length : 0;
    const baseCoverage = 60; // 基础覆盖率
    const bonusCoverage = Math.round(testRatio * 30); // 测试相关提交带来的额外覆盖率
    
    return Math.min(baseCoverage + bonusCoverage, 95); // 最高95%
  }

  /**
   * 计算代码质量分数
   */
  calculateQualityScore(commits, avgChangesPerCommit, testCoverage) {
    let score = 70; // 基础分数

    // 根据平均更改行数调整分数
    if (avgChangesPerCommit < 50) {
      score += 15; // 小提交加分
    } else if (avgChangesPerCommit > 200) {
      score -= 10; // 大提交减分
    }

    // 根据测试覆盖率调整分数
    if (testCoverage > 80) {
      score += 10;
    } else if (testCoverage < 50) {
      score -= 15;
    }

    // 根据提交信息质量调整分数
    const goodMessageRatio = this.calculateGoodMessageRatio(commits);
    score += Math.round(goodMessageRatio * 10);

    return Math.max(Math.min(score, 100), 0); // 确保分数在0-100之间
  }

  /**
   * 计算好的提交信息比例
   */
  calculateGoodMessageRatio(commits) {
    let goodMessages = 0;
    
    commits.forEach(commit => {
      const message = commit.title || commit.message || '';
      if (message.length > 10 && message.length < 100) {
        goodMessages++;
      }
    });

    return commits.length > 0 ? goodMessages / commits.length : 0;
  }

  /**
   * 生成AI总结
   */
  generateAISummary(commits, projectName, startDate, endDate) {
    const commitTypes = this.classifyCommits(commits);
    const totalCommits = commits.length;
    const avgChangesPerCommit = this.analyzeCodeQuality(commits).avgChangesPerCommit;
    const testCoverage = this.estimateTestCoverage(commits);

    const summary = `在 ${startDate} 至 ${endDate} 期间，${projectName} 项目共完成了 ${totalCommits} 个提交。

主要工作包括：
${commitTypes.feature > 0 ? `• 功能开发：${commitTypes.feature} 个新功能实现` : ''}
${commitTypes.bugfix > 0 ? `• Bug修复：${commitTypes.bugfix} 个问题修复` : ''}
${commitTypes.refactor > 0 ? `• 代码重构：${commitTypes.refactor} 次代码优化` : ''}
${commitTypes.docs > 0 ? `• 文档更新：${commitTypes.docs} 次文档维护` : ''}

代码质量分析：
• 平均每提交更改 ${avgChangesPerCommit} 行代码
• 估算测试覆盖率：${testCoverage}%
• 提交信息质量：${this.calculateGoodMessageRatio(commits) > 0.7 ? '良好' : '需要改进'}

团队协作效率良好，代码变更规模适中，测试覆盖率${testCoverage > 80 ? '较高' : '有提升空间'}。建议继续保持良好的提交习惯，适当增加测试用例覆盖。`;

    return summary;
  }
}

module.exports = AIAnalysisEngine;